package org.opengauss.evaluate;

import org.opengauss.evaluate.dao.AssessmentController;
import org.opengauss.evaluate.paeser.ParserController;
import org.opengauss.evaluate.paeser.command.Commander;
import org.opengauss.evaluate.paeser.config.AssessmentInfoManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

public class EvaluateAssessment {

	private static final Logger LOGGER = LoggerFactory.getLogger(EvaluateAssessment.class);
	private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 10,
			10L, TimeUnit.SECONDS, new LinkedBlockingQueue(100));

	public static void main(String[] args) throws Exception {
		args = new String[]{"-d","java","-c","assessment.properties","-o","C:\\Users\\biao.yang\\Desktop\\xxx\\report_collect.html","-w","1234"};
		sqlParsingThreadExecute(args);
		checkConditions();
		sqlAssessmentThreadExecute();

	}

	private static void checkConditions() {
		while (true) {
			if (Commander.isCommanderParseComplete()) {
				break;
			}
		}

		while (!AssessmentInfoManager.getInstance().getAssessmentFlag()) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException exp) {
				LOGGER.warn("main thread occur InterruptedException");
			}
		}

		if (LOGGER.isInfoEnabled()) {
			LOGGER.info("input file number is : " + AssessmentInfoManager.getInstance().getInputFileCount());
			LOGGER.info("output sqlfile number is : " + AssessmentInfoManager.getInstance().getOutputSqlFileCount());
		}
	}

	private static void sqlParsingThreadExecute(String[] args) throws Exception {
		ParserController parserController = new ParserController();
		parserController.setArgs(args);
		Future<?> future = threadPoolExecutor.submit(parserController);

		try {
			future.get();
		} catch (InterruptedException | ExecutionException e) {
			LOGGER.error("sqlParsing thread occur Exception, exit. exception ", e);
			threadPoolExecutor.shutdownNow();
			throw e;
		}
	}

	private static void sqlAssessmentThreadExecute() {
		AssessmentController assessmentController = new AssessmentController();
		Future future = threadPoolExecutor.submit(assessmentController);

		try {
			future.get();
		} catch (InterruptedException | ExecutionException e) {
			LOGGER.error("sqlAssessment thread occur Exception, exit. exception ", e);
			threadPoolExecutor.shutdownNow();
		}

		if (!threadPoolExecutor.isShutdown()) {
			threadPoolExecutor.shutdown();
		}
	}
}
